/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package batailledesardennes.util.geomFloat.path;

import batailledesardennes.util.geomFloat.GeomUtils;
import batailledesardennes.util.geomFloat.Point;
import batailledesardennes.util.geomFloat.Polygon;
import batailledesardennes.util.geomFloat.Rectangle;
import batailledesardennes.util.geomFloat.Shape;
import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author cghislai
 */
public class Obstacle {

    private Polygon polygon;
    private final List<Node> nodes;

    public Obstacle(Polygon polygon) {
        this.polygon = polygon;
        nodes = new ArrayList<Node>();
        calcNodes();
    }
    
    public Obstacle(Shape shape) {
        if (Rectangle.class.isAssignableFrom(shape.getClass())) {
            Rectangle rect = (Rectangle) shape;
            polygon = rect.toPolygon();
        } else if (Polygon.class.isAssignableFrom(shape.getClass())) {
            polygon = (Polygon) shape;
        } else {
            polygon = shape.getBoundsRect().toPolygon();
        }
        nodes = new ArrayList<Node>();
        calcNodes();
    }

    private void calcNodes() {
        final List<Point> points = polygon.getPoints();
        for (int i = 0; i < points.size(); i++) {
            Point p = points.get(i);
            int prevIdx = (i == 0 ? points.size() - 1 : i - 1);
            Point prevPoint = points.get(prevIdx);
            int nextIdx = (i + 1 >= points.size() ? 0 : i + 1);
            Point nextPoint = points.get(nextIdx);
            // check if concave
            int ccw = GeomUtils.ccw(prevPoint,p, nextPoint);
            if (polygon.isCounterClockWise()) {
                if (ccw > 0) {
                    continue;
                }
            } else {
                if (ccw < 0) {
                    continue;
                }
            }
            Node node = new Node(p);
            node.setObstacle(this);
            nodes.add(node);
        }
    }

    public List<Node> getNodes() {
        return nodes;
    }

    public Polygon getPolygon() {
        return polygon;
    }
}
